<template >
<div class="tcflefttofactory">
  <div>
    <el-breadcrumb @click="specialInitialProcess" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/initiatingprocess' }" v-if="isShowItem">{{process[processNumber]}}</el-breadcrumb-item>
      <span @click.stop=";" v-if="isShowSpan">{{process[processNumber]}}<i class="el-icon-arrow-right"></i> </span>
      <span @click.stop=";">TCF付尾款给工厂</span>
    </el-breadcrumb>
  </div>

  <el-tabs v-model="editableTabsValue" @tab-click="clickTabs" type="card">
    <el-tab-pane :key="item.name" v-for="(item, index) in editableTabsFixed" :label="item.title" :name="item.name">
      <quality-assurance :bus="flow4Bus" :editable="editable" :data="saveData.tcflefttofactory_qualityassurance" v-if="item.name === '1'" :formId="formIdStart + '_' + item.formId" />
      <left-apply :bus="flow4Bus" :editable="editable" :relation="relation" :data="saveData.tcflefttofactory_leftapply" :relatedData="saveData.tcflefttofactory_qualityassurance" v-else :formId="formIdStart + '_' + item.formId" />
    </el-tab-pane>
  </el-tabs>



  <div class="tcleftftofactory-bottom">
    <fixed-form v-if="hasBind" ref="fixedForm" :saveAndSend="saveAndSend" :editable="editable" :saveData="saveData" :sendMenus="sendMenus" processName="tcflefttofactory" />
    <fixed-form v-else  ref="fixedForm" :saveAndSend="false" :editable="false" :saveData="saveData" :sendMenus="sendMenus" processName="tcflefttofactory" />
  </div>

</div>
</template>

<script>

import Vue from 'vue';
import qualityAssurance from './components/qualityAssurance.vue';
import leftApply from './components/leftApply.vue';

import fixedForm from '../common/fixedForm.vue'

import {
  getSendMenus,
  getData,
} from '@/server/initiatingprocess'
import {
  getStore
} from '@/assets/js/common'

export default {
  beforeRouteEnter(to, from, next) {

    let dom = document.querySelector('.initiatingprocess  .routers-ctrl');
    if (dom) {
      dom.style.zIndex = '-1';
    }

    next(vm => {

      if (to.query.tab){

        switch (to.query.tab) {
          case '1':
          vm.editableTabsValue = '1';
          break;
          case '2':
          vm.editableTabsValue = '2';
        }

        vm.$message({
          message: '请先绑定订单，否则无法保存和发送',
          type: 'warning',
          duration: 3000,
          showClose: true
        });
      }

      //从其他位置跳转过来
      if (to.query.dTab) {
        vm.editableTabsValue = '' + to.query.dTab;
        vm.processNumber = parseInt(to.query.itemStatus);

        vm.relation = false;
        vm.hasBind = true;

        vm.flow4Bus.$emit('has-bind');

        if (to.query.isHive == 1) {
          vm.$store.commit('tcflefttofactory/SET_SAVE');
          let params = {
            flowId: to.query.flowId,
            currNodeId: to.query.currNodeId
          };

          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName,
            isHive: 1
          }).then((response) => {

            let data = response.data.datas[0];


            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }

              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              if ((k == 'tl_checkedPayMethods') || ( k == 'tl_thisPaymentTypes') || (k == 'tl_nonPaymentTypes')) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });

            _.extend(vm.saveData, data);


            let approvalIndex, approvalFullName, names = [];

            if (data.role) {

              vm.editable = data.role.DEFAULT == 'W' ? true : false;
              vm.saveAndSend = vm.editable;

              let copyApprovals = _.cloneDeep(data.approvals);

              for (let i = 0; i < copyApprovals.length ; i++) {
                for (var prop in vm.saveData.originApprovals[i]) {
                  if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                    vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                  }
                }
              }

              vm.saveData.isSalesMan = false;
            } else {
              vm.saveData.isSalesMan = true;
            }



            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$forceUpdate();
              vm.$refs.fixedForm.$forceUpdate();
            });
          });

        } else {

          let params = {
            flowId: to.query.flowId,
            currNodeId: to.query.currNodeId
          };

          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName
          }).then((response) => {

            let data = response.data.datas[0];


            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {
                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }
              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              if ((k == 'tl_checkedPayMethods') || ( k == 'tl_thisPaymentTypes') || (k == 'tl_nonPaymentTypes')) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });

            _.extend(vm.saveData, data);


            let approvalIndex, approvalFullName, names = [];

            if (data.role) {
              data.role.forEach((e) => {
                if (e.itemName.indexOf("item") === -1) {
                  vm.saveData.roles[e.itemName] = e.permission;
                } else {
                  let num = Number(e.itemName[e.itemName.length - 1]) - 1;
                  if (e.permission == 'W') {
                    approvalIndex = num;
                  }
                }
              });


              vm.editable = vm.saveData.roles.tcflefttofactory_qualityassurance == 'W' ? true : false;
              vm.saveAndSend = true;

              let copyApprovals = _.cloneDeep(data.approvals);


              if (approvalIndex !== undefined) {
                if (approvalIndex >= 0) {
                  for (let i = 0; i <= approvalIndex; i++) {
                    if (copyApprovals[i]){
                      for (var prop in vm.saveData.originApprovals[i]) {
                        if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                          vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                        }
                      }
                      vm.saveData.originApprovals[i].approval_id =  '' + copyApprovals[i].id;
                    }
                  }
                }

                let date = new Date();
                vm.saveData.originApprovals[approvalIndex].rw = 'W';
                vm.saveData.originApprovals[approvalIndex].approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                vm.saveData.originApprovals[approvalIndex].approval_username = JSON.parse(getStore('userMsg')).userName;;

              } else if (copyApprovals.length > 0){
                for (let i = 0; i < copyApprovals.length; i++) {

                  for (var prop in vm.saveData.originApprovals[i]) {
                    if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                      vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                    }
                  }
                  vm.saveData.originApprovals[i].approval_id = '' + copyApprovals[i].id;
                }
              }


              vm.saveData.isSalesMan = false;
            } else {
              vm.saveData.isSalesMan = true;
            }



            getSendMenus(params).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.$forceUpdate();
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$refs.fixedForm.$forceUpdate();
            });
          });
        }



      }
    });
  },
  beforeRouteLeave(to, from, next){
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';
    if (!this.$store.state.tcflefttofactory.hasSaved){
      this.$confirm('您填写的内容尚未保存或发送,是否要离开?', '提示', {
        confirmButtonText: '离开',
        cancelButtonText: '留下',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        Array.prototype.forEach.call(document.getElementsByTagName('*'), (e) => {
          e.blur();
        });
        next(false);
      });
    } else {
      next();
    }
  },
  created() {
    this.qaRelatedData = this.$store.state.businessform.businessform_foreigntradecontract;

    //不知该关联哪个内贸合同？？？
    this.laRelatedData = this.$store.state.businessform.businessform_domestictradecontract[0];


    let state = _.cloneDeep(this.$store.state.tcflefttofactory);


    this.saveData = {
      roles: {}
    }, this.sendMenus = [];

    for (var prop in state) {
      this.saveData[prop] = state[prop];
    }

    this.flow4Bus = new Vue();
    let _this = this;
    this.flow4Bus.$on('bind-new-ftc', function(data){
      _this.hasBind =  data;
      _this.$forceUpdate();
    });
  },
  data() {
    return {
      isShowItem: false,
      isShowSpan: false,
      flow4Bus: null,
      hasBind: false,
      editable: true,
      saveAndSend: true,
      process: ['待发事项', '待办事项', '已办事项','发起流程'],
      processNumber: 3,
      editableTabsValue: '1',
      relation: true, //决定表格之间是否有关联，当从服务器端获取数据时，所有的表格都不会有关联,
      editableTabsFixed: [{
        name: '1',
        title: '质量确认函',
        formId: 'qualityassurance'
      }, {
        name: '2',
        title: '尾款付款申请单&通知书',
        formId: 'leftapply'
      }]
    }
  },
  props: {
    formIdStart: {
      type: String,
      required: true
    }
  },
  mounted() {
    //刷新浏览器时，避免重叠
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';




    getSendMenus({
      'flowId': 4
    }).then((response) => {
      this.sendMenus = response.data.datas[0];
      this.$forceUpdate();
    });

    //判断面包屑二级路由是否可退回
    let isCreatFlow = getStore('isCreatFlow');
    this.isShowItem = !isCreatFlow ? false : true;
    this.isShowSpan = !isCreatFlow ? true : false;
  },

  methods: {
    specialInitialProcess() {
      let cls = event.target.classList;
      if (cls.contains("el-icon-arrow-right") && cls.contains("el-breadcrumb__separator")) return;
      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    },
    clickTabs(curTab) {
    }
  },
  components: {
    qualityAssurance,
    leftApply,
    fixedForm
  }
}
</script>

<style lang="scss">
.tcflefttofactory {
    padding: 20px;

    i.el-breadcrumb__separator {
        margin: 0 !important;
    }

    i.el-breadcrumb__separator[class*=icon] {
        margin: 0 !important;
        padding: 0 9px !important;
    }

    .tcleftftofactory-bottom {
        margin-top: 20px;
        border: 1px solid #999;
    }
}
</style>
